import React, { Component, Fragment } from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import { connect } from 'dva'
import {
  Card,
  Button,
  Form,
  Input,
  Select,
  DatePicker,
  Spin,
  Modal,
  Radio,
  InputNumber
} from 'antd'
import MyPageTable from '@/components/MyPageTable'
import { onTableData, getParam } from '@/utils/utils.js'
import CopyToClipboard from '@/components/CopyToClipboard'
import moment from 'moment'
const { Option } = Select
const { RangePicker } = DatePicker
const { TextArea } = Input
import { getTimeDistance } from '@/utils/utils'
import { router } from 'umi'
import OrderService from '@/services/order'
@connect(({ order, loading }) => ({
  ...order,
  loading: loading.effects['order/queryReletOrderByCondition']
}))
@Form.create()
export default class RentRenewal extends Component {
  state = {
    current: 1,
    yunTime: getTimeDistance('month'),
    orderId: '',
    visible: '',
    radioValue: '',
    damageValue: '',
    expressList: []
  }
  componentDidMount() {
    console.log(this.props, 'props')
    this.onList(1, 10)
    const { dispatch } = this.props
    dispatch({
      type: 'order/PlateformChannel'
    })
  }
  onList = (pageNumber, pageSize, data = {}) => {
    const { dispatch } = this.props
    dispatch({
      type: 'order/queryReletOrderByCondition',
      payload: {
        pageSize,
        pageNumber,
        ...data
      }
    })
  }

  settleDia = (type, orderId, userOrderCashId, record) => {
    if (record.userViolationRecords && record.userViolationRecords[0]) {
      let radioValue = 'good'
      radioValue = record.damagePrice ? 'damage' : radioValue
      radioValue = record.lostPrice ? 'lose' : radioValue
      this.setState({
        checkValue: true,
        radioValue,
        damageValue: record.damagePrice || record.lostPrice
      })
    }
    this.setState({
      orderId,
      userOrderCashId,
      record,
      visible: type
    })
  }

  handleOk = e => {
    e.preventDefault()
    this.props.form.validateFields(['beizhu'], (err, values) => {
      if (!err) {
        const { dispatch } = this.props
        dispatch({
          type: 'order/orderRemark',
          payload: {
            orderId: this.state.orderId,
            remark: values.beizhu,
            orderType: '01'
          },
          callback: res => {
            this.setState({
              visible: false
            })
          }
        })
      }
    })
  }

  getExpressList = () => {
    OrderService.selectExpressList().then(res => {
      this.setState({
        deliverOptions: res || []
      })
    })
  }

  onRadioChange = e => {
    this.setState({
      radioValue: e.target.value
    })
  }

  confirmSettlement = () => {
    this.props.form.validateFields(
      ['penaltyAmount', 'cancelReason'],
      (err, fieldsValue) => {
        if (err) return
        const { orderId, radioValue, damageValue } = this.state
        const payload = {
          lossAmount: 0,
          damageAmount: 0,
          penaltyAmount: 0,
          settlementType: radioValue,
          ...fieldsValue,
          orderId
        }
        if (radioValue === '03') {
          payload.lossAmount = damageValue
        } else if (radioValue === '02') {
          payload.damageAmount = damageValue
        }
        OrderService.merchantsIssuedStatements(payload).then(res => {
          this.onList(1, 10)
          this.props.form.resetFields()
          this.handleCancel()
        })
      }
    )
  }

  damageValue = val => {
    this.setState({
      damageValue: val
    })
  }

  handleCancel = e => {
    console.log(e)
    this.setState({
      visible: ''
    })
  }

  handleSubmit = e => {
    e.preventDefault()
    this.props.form.validateFields((err, values) => {
      console.log('Received values of form: ', values)
      if (values.createDate && values.createDate.length < 1) {
        values.createTimeStart = ''
        values.createTimeEnd = ''
        this.setState(
          {
            datas: { ...values }
          },
          () => {
            this.onList(1, 10, { ...values })
          }
        )
      } else if (values.createDate) {
        values.createTimeStart = moment(values.createDate[0]).format(
          'YYYY-MM-DD HH:mm:ss'
        )
        values.createTimeEnd = moment(values.createDate[1]).format(
          'YYYY-MM-DD HH:mm:ss'
        )
        this.setState(
          {
            datas: { ...values }
          },
          () => {
            this.onList(1, 10, { ...values })
          }
        )
      } else {
        this.setState(
          {
            datas: { ...values }
          },
          () => {
            this.onList(1, 10, { ...values })
          }
        )
      }
    })
  }
  // 重置
  handleReset = e => {
    this.props.form.resetFields()
    this.handleSubmit(e)
  }
  //table 页数
  onPage = e => {
    this.setState(
      {
        current: e.current
      },
      () => {
        this.onList(e.current, 10, this.state.datas)
      }
    )
  }
  onexport = () => {
    const { yunTime } = this.state
    if (this.props.form.getFieldValue('createDate')) {
      this.props.dispatch({
        type: 'order/exportOpeAllUserOrders',
        payload: {
          createTimeEnd: moment(
            this.props.form.getFieldValue('createDate')[1]
          ).format('YYYY-MM-DD HH:mm:ss'),
          createTimeStart: moment(
            this.props.form.getFieldValue('createDate')[0]
          ).format('YYYY-MM-DD HH:mm:ss')
        }
      })
    } else {
      this.props.dispatch({
        type: 'order/exportOpeAllUserOrders',
        payload: {
          createTimeEnd: moment(yunTime[1]).format('YYYY-MM-DD HH:mm:ss'),
          createTimeStart: moment(yunTime[0]).format('YYYY-MM-DD HH:mm:ss')
        }
      })
    }
  }
  confirm = () => {}

  showModal = (orderId, type) => {
    this.setState({
      visible: type,
      orderId
    })
  }

  render() {
    const { ReletList, ReletTotal, PlateformList, loading } = this.props
    const paginationProps = {
      current: this.state.current,
      pageSize: 10,
      total: ReletTotal,
      showTotal: total => (
        <span style={{ fontSize: '14px' }}>
          <span>共{Math.ceil(total / 10)}页</span>&emsp;
          <span>共{total}条</span>
        </span>
      )
    }
    let detailsStute = {
      '01': '待支付',
      '02': '支付中',
      '03': '已支付申请关单',
      '04': '待发货',
      '05': '待确认收货',
      '06': '租用中',
      '07': '待结算',
      '08': '结算待支付',
      '09': '订单完成',
      '10': '交易关闭'
    }
    const columns = [
      {
        title: '订单编号',
        dataIndex: 'orderId',
        width: '8%',
        render: orderId => <CopyToClipboard text={orderId} />
      },
      {
        title: '渠道来源',
        width: '10%',
        dataIndex: 'channelName'
      },
      {
        title: '商品名称',
        dataIndex: 'productName',
        width: '10%'
      },
      {
        title: '原订单号',
        width: '10%',
        render: e => {
          return (
            <div>
              <a
                className="primary-color"
                // onClick={() => router.push(`/Order/Details?id=${e.originalOrderId}`)}
                href={`#/Order/RentRenewal/Details?id=${e.originalOrderId}`}
                target="_blank"
              >
                {e.originalOrderId}
              </a>
            </div>
          )
        }
      },
      {
        title: '当前租期',
        dataIndex: 'currentPeriods',
        width: '7%'
      },
      {
        title: '总租金',
        render: e => <span>{e.totalRentAmount}</span>,
        width: '7%'
      },
      {
        title: '已付租金',
        render: e => <span>{e.payedRentAmount}</span>,
        width: '7%'
      },
      {
        title: '下单人姓名',
        width: '7%',
        render: e => <span>{e.realName}</span>
      },
      {
        title: '手机号',
        width: '7%',
        render: e => <span>{e.telephone}</span>
      },
      {
        title: '起租时间',
        width: '7%',
        render: e => {
          return <>{e.rentStart}</>
        }
      },
      {
        title: '归还时间',
        width: '7%',
        render: e => {
          return <>{e.unrentTime}</>
        }
      },
      {
        title: '下单时间',
        dataIndex: 'placeOrderTime',
        width: '7%'
      },
      {
        title: '订单状态',
        dataIndex: 'status',
        width: '10%',
        render: status => {
          return <span>{detailsStute[status]}</span>
        }
      },
      {
        title: '操作',
        width: '80px',
        fixed: 'right',
        render: (e, record) => {
          return (
            <div style={{ textAlign: 'center' }}>
              <a
                className="primary-color"
                // onClick={() =>
                //   router.push(`/Order/Details?id=${e.orderId}&RentRenewal=RentRenewal`)
                // }
                href={`#/Order/RentRenewal/Details?id=${e.orderId}&RentRenewal=RentRenewal`}
                target="_blank"
              >
                处理
              </a>
              {/*<br />*/}
              {/*<a className="primary-color" onClick={() => this.showModal(e.orderId, 'remark')}>*/}
              {/*  备注*/}
              {/*</a>*/}
              {/*{record.status === '07' ? (*/}
              {/*  <Fragment>*/}
              {/*    <br />*/}
              {/*    <a*/}
              {/*      className="primary-color"*/}
              {/*      onClick={() =>*/}
              {/*        this.settleDia('settle', record.orderId, record.orderCashId, record)*/}
              {/*      }*/}
              {/*    >*/}
              {/*      结算*/}
              {/*    </a>*/}
              {/*  </Fragment>*/}
              {/*) : null}*/}
            </div>
          )
        }
      }
    ]
    const { getFieldDecorator } = this.props.form
    const {
      visible,
      deliverOptions,
      radioValue,
      damageValue,
      record
    } = this.state

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      }
    }

    return (
      <PageHeaderWrapper>
        <Card bordered={false}>
          <Form layout="inline" onSubmit={this.handleSubmit}>
            <Form.Item label="商品名称">
              {getFieldDecorator(
                'productName',
                {}
              )(<Input allowClear placeholder="请输入商品名称" />)}
            </Form.Item>
            <Form.Item label="下单人姓名">
              {getFieldDecorator(
                'userName',
                {}
              )(<Input allowClear placeholder="请输入下单人姓名" />)}
            </Form.Item>
            <Form.Item label="下单人手机号">
              {getFieldDecorator(
                'telephone',
                {}
              )(<Input allowClear placeholder="请输入下单人手机号" />)}
            </Form.Item>
            <Form.Item label="订单编号">
              {getFieldDecorator(
                'orderId',
                {}
              )(<Input allowClear placeholder="请输入订单编号" />)}
            </Form.Item>
            <Form.Item label="创建时间">
              {getFieldDecorator('createDate', {})(<RangePicker allowClear />)}
            </Form.Item>
            <Form.Item label="订单状态">
              {getFieldDecorator(
                'state',
                {}
              )(
                <Select
                  placeholder="订单状态"
                  allowClear
                  style={{ width: 180 }}
                >
                  <Option value="01">待支付</Option>
                  {/* <Option value="03">已支付申请关单</Option> */}
                  <Option value="04">待发货</Option>
                  <Option value="05">待确认收货</Option>
                  <Option value="06">租用中</Option>
                  <Option value="07">待结算</Option>
                  <Option value="08">结算待支付</Option>
                  <Option value="09">订单完成</Option>
                  <Option value="10">交易关闭</Option>
                </Select>
              )}
            </Form.Item>
            <div>
              <Form.Item>
                <Button type="primary" htmlType="submit">
                  查询
                </Button>
              </Form.Item>
              <Form.Item>
                <Button htmlType="button" onClick={this.handleReset}>
                  重置
                </Button>
              </Form.Item>
              <Form.Item>
                <Button onClick={this.onexport}>导出</Button>
              </Form.Item>
            </div>
          </Form>
          <Spin spinning={loading}>
            <MyPageTable
              scroll
              onPage={this.onPage}
              paginationProps={paginationProps}
              dataSource={onTableData(ReletList)}
              columns={columns}
            />
          </Spin>
          <Modal
            title="备注"
            visible={visible === 'remark'}
            onOk={this.handleOk}
            onCancel={this.handleCancel}
          >
            <Form>
              <Form.Item label="备注内容" {...formItemLayout}>
                {getFieldDecorator('beizhu', {
                  rules: [{ required: true, message: '请输入备注' }]
                })(<TextArea placeholder="请输入" />)}
              </Form.Item>
            </Form>
          </Modal>
          <Modal
            title="是否确认结算？"
            zIndex={2000}
            visible={visible === 'settle'}
            onOk={this.confirmSettlement}
            onCancel={this.handleCancel}
          >
            <div>
              <div>
                <span style={{ marginRight: '20px' }}>宝贝状态</span>
                <Radio.Group onChange={this.onRadioChange} value={radioValue}>
                  <Radio value="01">完好</Radio>
                  <Radio value="02">损坏</Radio>
                  <Radio value="03">丢失</Radio>
                  <Radio value="04">其他</Radio>
                </Radio.Group>
                {radioValue === '02' && (
                  <div style={{ display: 'inline-block' }}>
                    <span>损坏赔偿金：</span>
                    <InputNumber
                      min={0}
                      defaultValue={0}
                      value={damageValue}
                      onChange={this.damageValue}
                    />
                    <span>元</span>
                  </div>
                )}
                {radioValue === '03' && (
                  <div style={{ display: 'inline-block' }}>
                    <span>丢失赔偿金：</span>
                    <InputNumber
                      min={0}
                      defaultValue={0}
                      value={damageValue}
                      onChange={this.damageValue}
                    />
                    <span>元</span>
                  </div>
                )}
                {radioValue === '04' && (
                  <div>
                    <Form.Item labelCol={{ span: 4 }} label="违约金：">
                      {form.getFieldDecorator('penaltyAmount', {
                        initialValue: record.penaltyAmount
                      })(<InputNumber min={0} />)}
                      <span> 元</span>
                    </Form.Item>
                    <Form.Item labelCol={{ span: 4 }} label="违约原因：">
                      {form.getFieldDecorator('cancelReason', {
                        initialValue: record.cancelReason
                      })(
                        <Input
                          style={{ width: '60%' }}
                          placeholder="请输入违约原因"
                        />
                      )}
                    </Form.Item>
                  </div>
                )}
              </div>
            </div>
          </Modal>
        </Card>
      </PageHeaderWrapper>
    )
  }
}
